package com.CloudDream.Command.Player;

import com.CloudDream.Inventory.InventoryItem;
import com.CloudDream.MoonCake;
import com.handy.lib.command.IHandyCommandEvent;
import com.handy.lib.util.BaseUtil;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitRunnable;

import java.util.ArrayList;
import java.util.List;

public class GiftCommand implements IHandyCommandEvent {

    private MoonCake instance = MoonCake.getInstance();

    @Override
    public String command() {
        return "gift";
    }

    @Override
    public String permission() {
        return "mooncake.gift";
    }

    @Override
    public void onCommand(final CommandSender commandSender, Command command, String s, String[] strings) {
        if(BaseUtil.isNotPlayer(commandSender).booleanValue()){
            commandSender.sendMessage(MoonCake.prefix + "§7该命令只能由玩家执行");
            return;
        }

        Player p = (Player) commandSender;
        String m = "Message.";
        List<String> l = new ArrayList<String>();
        (new BukkitRunnable(){
            @Override
            public void run() {
                for (int i = 0; i < 40; ++i) {
                    ItemStack pi = p.getInventory().getItem(i);
                    if (pi != null) {
                        for (int c = 0; c < 7; c++) {
                            if (pi.equals(InventoryItem.getMoonCake(c)) && !l.contains(String.valueOf(p))) {
                                l.add(String.valueOf(c));
                            }
                        }
                    }
                    if (i == 39) {
                        if (l.size() == 7) {
                            for (int n = 0; n < 40; ++n) {
                                ItemStack pi2 = p.getInventory().getItem(n);
                                if (pi2 != null) {
                                    //循环计算
                                    for (int u = 0; u < 7; u++) {
                                        if (pi2.equals(InventoryItem.getMoonCake(u)) && l.contains(String.valueOf(u))) {
                                            l.remove(String.valueOf(u));
                                            pi2.setAmount(pi2.getAmount() - 1);
                                        }
                                    }
                                }
                            }
                            p.getInventory().addItem(InventoryItem.getGift());
                            p.sendMessage(MoonCake.prefix + instance.getConfig().getString(m + ".Compose-Gift"));
                        }
                        p.sendMessage(MoonCake.prefix + instance.getConfig().getString(m + ".Error-3"));
                    }
                }
            }
        }).runTaskAsynchronously(MoonCake.getInstance());
    }
}
